<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-form-item label="客户名称">
              <a-tree-select
                style="width:100%"
                :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                :treeData="treeData"
                v-model="queryParam.customerId"
                placeholder="请选择客户名称"
                @select="loadTree"
                :disabled="disableSubmit">
              </a-tree-select>
              <!--<a-input placeholder="请输入客户名称" v-model="queryParam.customerName"></a-input>-->
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="设备ID">
              <a-input placeholder="请输入设备ID" v-model="queryParam.deviceId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="使用状态">
              <a-select placeholder="请输入使用状态"  v-model="queryParam.status">
                <a-select-option value="0">未试用</a-select-option>
                <a-select-option value="1">已试用</a-select-option>
                <a-select-option value="2">已激活</a-select-option>
                <a-select-option value="3">试用过期</a-select-option>
                <a-select-option value="4">激活过期</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24" >
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleConfig" type="primary" icon="plus">批量配置</a-button>
      <!--<a-button type="primary" icon="download" @click="handleExportXls('device_activation')">导出</a-button>-->
      <a-button type="primary" icon="download" @click="()=>modal.visible=true">设备导入</a-button>
      <a href="../../devices.xlsx" download="设备导入模板.xlsx" target="_blank">下载设备导入模板</a>
      <!--@click="handleExportXls('订水申请')"-->
      <a-modal
        :visible="modal.visible"
        :width="modal.width"
        :style="modal.style"
        :destroyOnClose="true"
        @ok="handleQr"
        @cancel="()=>modal.visible=false">

        <template>
          <!--地图模块-->
          <a-form-item  label="客户名称"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
            <a-tree-select
              style="width:100%"
              :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
              :treeData="treeData"
              v-model="customerId"
              placeholder="请选择客户名称"
              @select="loadTree"
              :disabled="disableSubmit">
            </a-tree-select>
          </a-form-item>
          <a-form-item  label="设备文件上传"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileUrl">
           <a-input v-model="fileUrl" placeholder="可直接填入文件地址" style="width:260px" clearable/>
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="uploadAction" :beforeUpload="beforeUpload" @change="handleChange">
              <a-button type="primary" icon="import">上传</a-button>
            </a-upload>
          </a-form-item>
        </template>

      </a-modal>

      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <!--<a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="record.useStatus==0 && record.trialDuration==null" @click="handleEdit(record)">配置</a>

          <!--<a-divider type="vertical" />
           <a @click="handleDetail(record)">详情</a>-->
          <!--<a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              &lt;!&ndash;<a-menu-item>
                <a-popconfirm title="确定配置吗?" @confirm="() => handleConfig(record.id)">
                  <a>配置</a>
                </a-popconfirm>
              </a-menu-item>&ndash;&gt;
              &lt;!&ndash;<a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>&ndash;&gt;
            </a-menu>
          </a-dropdown>-->
        </span>

      </a-table>
    </div>

    <!--<device-activation-modal ref="modalForm" @ok="modalFormOk"></device-activation-modal>-->
    <device-config-modal ref="modalForm" @ok="modalFormOk"></device-config-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { XuRuiListMixin } from '@/mixins/XuRuiListMixin'
  /*import DeviceActivationModal from './modules/DeviceActivationModal'*/
  import DeviceConfigModal from './modules/DeviceConfigModal'

  import {queryKHTreeList,sbImport } from '@/api/api'

  export default {
    name: 'DeviceActivationList',
    mixins:[XuRuiListMixin, mixinDevice],
    components: {
      DeviceConfigModal
      /*DeviceActivationModal*/
    },
    data () {
      return {
        modal: {
          title: '客户选择',
          visible: false,
          width: '45%',
          style: { top: '20px' },
          fullScreen: false
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        customerId:'',
        fileUrl:'',
        description: 'device_activation管理页面',
        // 表头
        columns: [
          /*{
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },*/
          {
            title:'设备ID',
            align:"center",
            dataIndex: 'deviceId'
          },
          {
            title:'使用状态',
            align:"center",
            dataIndex: 'useStatus_dictText'
          },
          {
            title:'试用开始时间',
            align:"center",
            dataIndex: 'trialStartTime',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'试用结束时间',
            align:"center",
            dataIndex: 'trialEndTime',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'试用时长',
            align:"center",
            dataIndex: 'trialDuration'
          },
          {
            title:'激活开始时间',
            align:"center",
            dataIndex: 'activationStartTime',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'激活结束时间',
            align:"center",
            dataIndex: 'activationEndTime',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'激活时长',
            align:"center",
            dataIndex: 'activationDuration'
          },
          {
            title:'客户名称',
            align:"center",
            dataIndex: 'customerId_dictText'
          },
          {
            title:'安卓费用',
            align:"center",
            dataIndex: 'androidCost'
          },
          {
            title:'IOS费用',
            align:"center",
            dataIndex: 'iosCost'
          },
         /* {
            title:'是否删除(0未删除 1已删除)',
            align:"center",
            dataIndex: 'deleted'
          },*/
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          fileUpload: window._CONFIG['domianURL']+"/sys/common/upload",
          list: "/device/deviceActivation/list",
          delete: "/device/deviceActivation/delete",
          deleteBatch: "/device/deviceActivation/deleteBatch",
          exportXlsUrl: "/device/deviceActivation/exportXls",
          importExcelUrl: "device/deviceActivation/importExcel",
          
        },
        dictOptions:{},
        superFieldList:[],
        disableSubmit:false,
        treeData:[],
      }
    },
    created() {
    this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      uploadAction:function () {
        return this.url.fileUpload;
      }

    },
    methods: {
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'deviceId',text:'设备ID'})
        fieldList.push({type:'string',value:'useStatus',text:'使用状态(0.未试用、1.已试用、2.已激活)'})
        fieldList.push({type:'date',value:'trialStartTime',text:'试用开始时间'})
        fieldList.push({type:'date',value:'trialEndTime',text:'试用结束时间'})
        fieldList.push({type:'int',value:'trialDuration',text:'试用时长'})
        fieldList.push({type:'date',value:'activationStartTime',text:'激活开始时间'})
        fieldList.push({type:'date',value:'activationEndTime',text:'激活结束时间'})
        fieldList.push({type:'int',value:'activationDuration',text:'激活时长'})
        fieldList.push({type:'string',value:'customerId',text:'客户ID'})
        fieldList.push({type:'number',value:'androidCost',text:'安卓费用'})
        fieldList.push({type:'number',value:'iosCost',text:'IOS费用'})
        fieldList.push({type:'int',value:'deleted',text:'是否删除(0未删除 1已删除)'})
        this.superFieldList = fieldList
        this.loadTree();
      },
      handleConfig(){
          let ids = "";
        this.selectedRowKeys.forEach(function (val) {
            ids += val + ",";
          });
        if(ids==""){
          this.$refs.modalForm.add(ids);
        }else{
          var param={'ids':ids,"type":'pl'};
          this.$refs.modalForm.edit(param);
        }

        this.$refs.modalForm.title = "批量配置";
        this.$refs.modalForm.disableSubmit = false;
      },
      loadTree(){
        var that = this;
        queryKHTreeList().then((res)=>{
          if(res.success){
            console.log('----queryKHTreeList---')
            console.log(res)
            that.treeData = [];
            let treeList = res.result.treeList
            for(let a=0;a<treeList.length;a++){
              let temp = treeList[a];
              // temp.isLeaf = temp.leaf;
              that.treeData.push(temp);
            }
          }
        });
      },
    beforeUpload: function(file){
      var fileName = file.name;
      var pos=fileName.lastIndexOf(".");
      var lastName=fileName.substring(pos,fileName.length);
      console.log(lastName,lastName.toLowerCase())
      if(lastName.toLowerCase()!==".xls" && lastName.toLowerCase()!==".xlsx"){
        this.$message.warning('请上传Excel');
        return false;
      }
      //TODO 验证文件大小
    },
    handleChange (info) {
      debugger;
      if (info.file.status === 'uploading') {
        this.uploadzpLoading = true;
        return
      }
      if (info.file.status === 'done') {
        debugger;
        var response = info.file.response;
        this.uploadzpLoading = false;
        console.log(response);
        if(response.success){
          this.fileUrl = response.message;
        }else{
          this.$message.warning(response.message);
        }
      }
    },
      handleQr(){
        debugger
        let param = {'customerId':this.customerId,'fileUrl':this.fileUrl};
        var that=this;
        sbImport(param).then((data)=>{
          debugger
        console.log(data)
          that.modal.visible=false;
          that.$message.success(data.message)
        });
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>